<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0,user-scalable=no">
    </meta>
    <meta http-equiv="Cache" content="no-cache">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Expires" content="0" />
    <script type="text/javascript" src="./articleAxios.min.js"></script>
    <script src="./articleServer.js"></script>
    <script src="./utils.js"></script>
    <!--wangeditor编辑器-->
    <link href="./editor.css" rel="stylesheet">
    <script src="./editor.js"></script>
    <!--用于DOM操作的js库 -->
    <script src="./dom7.js"></script>
    <!-- <script type="text/javascript" src="./eruda.js"></script>
    <script>eruda.init({
            container: document.getElementById("editor—wrapper"),
            useShadowDom: false
        });
    </script> -->
    <!--虚拟dom库 -->
    <script src="./snabbdom.cjs.js"></script>
    <!--slate编辑器-->
    <script src="./slate.js"></script>
    <!--自定义元素-->
    <script src="./customVideo.js"></script>
    <script src="./customElem.js"></script>
    <script src="./customTitle.js"></script>
    <script src="./customTitle2.js"></script>
    <script src="./customTitle3.js"></script>
    <script src="./customBlockquote.js"></script>
    <script src="./customEmoji.js"></script>
    <script src="./customImage.js"></script>
    <style>
        .eruda-container {
            position: relative;
        }

        #editor—wrapper {
            border: none;
            z-index: 100;
            /* 按需定义 */
        }

        #toolbar-container {
            display: block;
            /* border-bottom: 1px solid #ccc; */
        }

        #editor-container {
            height: auto;
            min-height: calc(100vh - 68px);
        }

        .textarea-title {
            border: none;
            max-height: 68px;
            width: 100%;
            margin: 0 7px;
            border-bottom: 1px solid #e2e5eb;
            font-family: PingFang SC, PingFang SC-Bold;
            line-height: 33.5px;
            font-size: 21px;
            font-weight: 700;
            color: #1a1c27;
        }

        .textarea-title::-webkit-scrollbar {
            width: 0 !important
        }

        textarea:focus {
            outline: 1px solid transparent;
        }

        .title—wrapper {
            display: flex;

        }

        textarea::placeholder {
            color: #9597a0;
            line-height: 33.5px;
            font-size: 21px;
            font-family: PingFang SC, PingFang SC-Bold;
            font-weight: 700;
        }

        .w-e-text-container [data-slate-editor] {
            min-height: calc(100vh - 68px);
        }
    </style>

</head>

<body>
    <div>
        <div id="obj"></div>
        <div id="obj2"></div>
        <button onclick="setSelectionStyle({
            attribute:'style_cite_1',
            state:1

        })"> 'style_cite_1</button>
        <button onclick="setSelectionStyle({
            attribute:'style_cite_2',
            state:1

        })"> 'style_cite_2'
        </button>
        <button onclick="setSelectionStyle({
            attribute:'style_cite_3',
            state:1

        })"> 'style_cite_3'
        </button>
        <button onclick="setSelectionStyle({
            attribute:'font_align_default_1',
            state:1

        })"> 'font_align_default_1</button>


        <button onclick="setEditorHtml({
           files,
           content,
           title:`ddd`

        })"> 'setEditorHtml</button>

        <button data-menu-key="color" onclick="setSelectionStyle({
            attribute:'font_color_#FE7429_4',
            state:1

        })"> 颜色</button>
        <button onclick="setSelectionStyle({
            attribute:'font_color_#00AA54_5',
            state:1

        })"> 颜色2</button>

        <button onclick="deleteForward(

        )">删除</button>

        <div class="title—wrapper">
            <textarea id="title" class="textarea-title" type="text" placeholder="请输入标题（2~30个字）" rows="1" maxLength="30"
                onfocus="titleEditorClick()" onInput="titleInput()"></textarea>
        </div>
        <div id="editor—wrapper">
            <div id="toolbar-container" style="display: none;"></div>
            <div id="editor-container" onclick="editorClick(event)">
            </div>
        </div>
    </div>
    <script>

        const version = "1.0.22"
        let saveDraftShow = false
        var editorHtmlShow = false
        var files = [{"duration":0,"id":"8bc4e412d9f047318eb3c7306633c521","path":"/storage/emulated/0/Pictures/xinlanedit/tietu1754308516063.png"},{"duration":6720,"id":"1b3cbd77a91f4d3c80d52e8d61e35efe","path":"/storage/emulated/0/DCIM/Camera/20250804_194656.mp4"}]
        var content = `<html xmlns="http://www.w3.org/1999/xhtml">
                                                                                                     <head>
                                                                                                      <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
                                                                                                      <meta charset="UTF-8">
                                                                                                      <meta http-equiv="Pragma" content="no-cache">
                                                                                                      <title></title>
                                                                                                     </head>
                                                                                                     <body>
                                                                                                      <div id="bodybox">
                                                                                                       <p><br></p>
                                                                                                       <p><img data-w-e-type="customImage" id="8bc4e412d9f047318eb3c7306633c521" data-file-id="" src="http://vod-c2.zzdnews.com/a5otvrbrgwlc0exn/cover/article/dev/260796098981134336/zzd_android_1008x756_tietu1754308516063.png" alt="" data-href="/storage/emulated/0/Pictures/xinlanedit/tietu1754308516063.png" style="" data-md5="a5f18fa780a047a49710722c967d4a70" data-error="/"></p>
                                                                                                       <p><br></p>
                                                                                                       <p>
                                                                                                        <video poster="" data-w-e-type="thumbnail" width="100%" src="/storage/emulated/0/DCIM/Camera/20250804_194656.mp4" data-file-id="" cover-file-id="" data-duration="6720" controls="" data-thumb="/storage/emulated/0/DCIM/Camera/20250804_194656.mp4" data-href="/storage/emulated/0/DCIM/Camera/20250804_194656.mp4" data-style="512,288" id="1b3cbd77a91f4d3c80d52e8d61e35efe" data-md5=""></video></p>
                                                                                                       <p><br></p>
                                                                                                      </div>
                                                                                                     </body>
                                                                                                    </html>
                                                                                                `

        //编辑器生命周期
        document.write("<script src='./editorMain.js?" + version + "'><\/script>");
        //在输入面板弹出的状态下滚动需收起输入面板
        document.addEventListener("touchmove", (e) => {
            if (!keyboardUp) return
            window.android ? window.android.keyboardShow("0") : window.webkit.messageHandlers.keyboardShow.postMessage("0");
        })
        //编辑器不保存,false时不给app传数据
        var notSave = false
        const { Editor, withHistory } = window.Slate;
        //类vue2,数据监听,无递归,只处理一层
        let myData = {
            index: 0,
            computedCount: 0,
            html: "",
            imgCount: 0,
            imgComplete: 0,
            imgs: [],
            imgList: []
        }
        //img编辑器定位信息存储
        let imgLocaltion = [];
        let myWatch = new Watch(myData)
        let vm = {}
        vm._data = data = myWatch;
        function Watch(obj) {
            //获取对象中的每一个属性
            const myKey = Object.keys(obj)
            myKey.forEach(key => {
                // 此处的this指向构造函数的实例
                Object.defineProperty(this, key, {
                    get() {
                        return obj[key]
                    },
                    set(val) {
                        obj[key] = val
                        if (document.getElementById("title").value != '') {
                            saveDraftShow = true
                        } else {
                            saveDraftShow = false
                        }
                        if (key == "imgComplete" && vm._data.imgCount > 0 && vm._data.imgComplete == vm._data.imgCount) {
                            vm._data.imgList.forEach(i => {
                                vm._data.imgs.forEach(item => {
                                    if (i == item.el) {
                                        let node1 = { type: 'paragraph', children: [{ text: '' }] }
                                        SlateTransforms.insertNodes(editor, [node1])
                                        let node = { type: 'customImage', href: item.el, uuid: generateUUID().replace(/-/g, ''), src: item.dataUrl, children: [{ text: '' }], error: item.dataUrl == "./file_error.jpeg" ? true : false }
                                        SlateTransforms.insertNodes(editor, [node])
                                        editor.insertBreak()
                                    }
                                })
                            })
                            vm._data.imgCount = 0
                            vm._data.imgComplete = 0
                            vm._data.imgs = []
                            window.android ?
                                window.android.editorReady(saveDraftShow) :
                                window.webkit.messageHandlers.editorReady.postMessage(saveDraftShow)
                        }
                        //当草稿里所有需要异步加载的数据都成功之后触发,设置数据
                        if (key == "computedCount" && vm._data.computedCount == vm._data.index) {
                            if (document.getElementById("title").scrollHeight > document.getElementById("title").clientHeight) {
                                document.getElementById("title").style.height = "auto";
                                document.getElementById("title").scrollTop = 0; // 防抖动
                                document.getElementById("title").style.height = 68 + "px";
                            }
                            vm._data.html = new XMLSerializer().serializeToString(vm._data.html)
                            vm._data.html = vm._data.html.replace(/video/gi, "img")
                            vm._data.html = vm._data.html.replace(/[\r\n]/gi, "")
                            editor.setHtml(vm._data.html.slice(vm._data.html.indexOf("bodybox") + 9, vm._data.html.indexOf("</div></body>")))
                            editor.focus(true);
                            setTimeout(() => {

                                window.android ?
                                    window.android.editorReady(saveDraftShow) :
                                    window.webkit.messageHandlers.editorReady.postMessage(saveDraftShow);
                                notSave = false
                            }, 300)
                        }
                    }
                })

            });
        }
        //标题切换中文拼音时不调保存
        let znFlag = false;
        let currentTitle = document.getElementById("title").value
        let keyboardUp;
        var originalHeight = document.documentElement.clientHeight || document.body.clientHeight;
        document.getElementById("title").addEventListener(
            "compositionend", function () {
                if (currentTitle != document.getElementById("title").value) {
                    currentTitle = document.getElementById("title").value
                    znFlag = false
                    window.android ?
                        window.android.saveDraft(JSON.stringify(getEditorHtml(1))) :
                        window.webkit.messageHandlers.saveDraft.postMessage(JSON.stringify(getEditorHtml(1)))
                }
            }
        )
        document.getElementById("title").addEventListener(
            "compositionstart", function () {
                znFlag = true
            }
        )
        function keyboardState(e) {
            if (e == 1) {
                keyboardUp = true
            } else if (e == 0) {
                keyboardUp = false
            }
        }
        function titleInput() {
            if (!znFlag && currentTitle != document.getElementById("title").value) {
                if (document.getElementById("title").value != '') {
                    saveDraftShow = true
                } else {
                    saveDraftShow = false
                }
                currentTitle = document.getElementById("title").value
                window.android ?
                    window.android.saveDraft(JSON.stringify(getEditorHtml())) :
                    window.webkit.messageHandlers.saveDraft.postMessage(JSON.stringify(getEditorHtml()))
            }
        }
        //app选完图片点击完成
        function addImages(imgs) {
            vm._data.imgList = imgs
            imgs.forEach((el, index) => {
                request({
                    method: "get",
                    url: "/interceptShaLou" + el,
                    responseType: "blob"
                }).then(async res => {
                    let dataUrl = await fileToBase64Async(res.data)
                    if (!res.data.size) {
                        dataUrl = "./file_error.jpeg"
                    }
                    if (index == 0) {
                        vm._data.imgCount = imgs.length
                        vm._data.imgs.length = imgs.length
                    }
                    if (index == 0 && editor.selection === null) editor.restoreSelection()
                    if (dataUrl) {
                        // vm._data.imgs.splice(index, 0, { dataUrl: dataUrl, el: el });
                        vm._data.imgs.push({ dataUrl: dataUrl, el: el })
                        vm._data.imgComplete++
                    }
                }).catch(err => {
                    console.log(err)
                })
            });
            return;
        }
        function addImagesIos(imgs) {
            vm._data.imgList = imgs

            imgs.forEach((el, index) => {
                fetch('customhttps://dasdasd/interceptShaLou/' + el)
                    .then(response => {
                        if (!response.ok) throw new Error('Network response was not ok');
                        return response.blob(); // 使用blob()接收二进制数据
                    })
                    .then(async blob => {

                        let dataUrl = await new Promise((resolve) => {
                            const reader = new FileReader();
                            reader.onloadend = () => resolve(reader.result);
                            reader.readAsDataURL(blob);
                        });

                        if (index == 0) {
                            vm._data.imgCount = imgs.length;
                            vm._data.imgs.length = imgs.length;
                        }
                        if (index == 0 && editor.selection === null) editor.restoreSelection();

                        if (dataUrl) {
                            vm._data.imgs.push({ dataUrl: dataUrl, el: el });
                            vm._data.imgComplete++;
                        }
                    })
                    .catch(err => {
                        console.error('Error:', err);
                        vm._data.imgs.push({ dataUrl: "./file_error.jpeg", el: el });
                        vm._data.imgComplete++;
                        document.getElementById("obj2").innerText = JSON.stringify(err)

                    });
            });
        }
        //点击编辑器图片编辑
        function imageEdit(imgUrl) {
            imgUrl.forEach(el => {
                request({
                    method: "get",
                    url: "/interceptShaLou" + el,
                    responseType: "blob"
                }).then(async res => {
                    let dataUrl = await fileToBase64Async(res.data)
                    if (!editor.selection) {
                        editor.restoreSelection()
                    }
                    SlateTransforms.removeNodes(editor, { at: editor.selection })
                    let node = { type: 'customImage', uuid: generateUUID().replace(/-/g, ''), href: el, src: dataUrl, children: [{ text: '' }] }
                    SlateTransforms.insertNodes(editor, [node])
                    editor.insertBreak()
                    window.android ?
                        window.android.editorReady(saveDraftShow) :
                        window.webkit.messageHandlers.editorReady.postMessage(saveDraftShow)
                }).catch(err => {
                    console.log(err)
                })
            })
        }
        function imageEditIos(imgUrl) {
            imgUrl.forEach(el => {
                fetch('customhttps://dasdasd/interceptShaLou/' + el)
                    .then(response => {
                        if (!response.ok) throw new Error('Network response was not ok');
                        return response.blob(); // 使用blob()接收二进制数据
                    })
                    .then(async res => {

                        let dataUrl = await new Promise((resolve) => {
                            const reader = new FileReader();
                            reader.onloadend = () => resolve(reader.result);
                            reader.readAsDataURL(res);
                        });

                        if (!editor.selection) {
                            editor.restoreSelection()
                        }
                        SlateTransforms.removeNodes(editor, { at: editor.selection })
                        let node = { type: 'customImage', uuid: generateUUID().replace(/-/g, ''), href: el, src: dataUrl, children: [{ text: '' }] }
                        SlateTransforms.insertNodes(editor, [node])
                        editor.insertBreak()
                        window.android ?
                            window.android.editorReady(saveDraftShow) :
                            window.webkit.messageHandlers.editorReady.postMessage(saveDraftShow)
                    })
                    .catch(err => {
                        console.log(err)
                    });
            })
        }
        //选完视频点击完成
        function addVideo(data) {
            request({
                method: "get",
                url: "/interceptShaLou" + data.path,
                responseType: "blob"
            }).then(async res => {
                let dataUrl = await fileToBase64Async(res.data)
                let img = new Image();
                let imgHeight;
                let imgWidth;
                img.src = dataUrl;
                if (img.complete) {
                    imgHeight = img.height
                    imgWidth = img.width
                    setTimeout(() => {
                        let node1 = { type: 'paragraph', children: [{ text: '' }] }
                        SlateTransforms.insertNodes(editor, [node1])
                        let node = { type: 'thumbnail', thumb: data.path, duration: data.duration, href: data.url, uuid: generateUUID().replace(/-/g, ''), src: dataUrl, style: { imgHeight: imgHeight, imgWidth: imgWidth }, children: [{ text: '' }] }
                        SlateTransforms.insertNodes(editor, [node])
                        editor.insertBreak()
                        window.android ?
                            window.android.editorReady(saveDraftShow) :
                            window.webkit.messageHandlers.editorReady.postMessage(saveDraftShow)
                    }, 100)
                } else {
                    img.onload = await function () {
                        imgHeight = img.height
                        imgWidth = img.width
                    }
                    setTimeout(() => {
                        let node1 = { type: 'paragraph', children: [{ text: '' }] }
                        SlateTransforms.insertNodes(editor, [node1])
                        let node = { type: 'thumbnail', thumb: data.path, duration: data.duration, href: data.url, uuid: generateUUID().replace(/-/g, ''), src: dataUrl, style: { imgHeight: imgHeight, imgWidth: imgWidth }, children: [{ text: '' }] }
                        SlateTransforms.insertNodes(editor, [node])
                        editor.insertBreak()
                        window.android ?
                            window.android.editorReady(saveDraftShow) :
                            window.webkit.messageHandlers.editorReady.postMessage(saveDraftShow)
                    }, 100)
                }
            }).catch(err => {
                console.log(err)
            })
        }

        //选完视频点击完成
        function addVideoIos(data) {
            fetch('customhttps://dasdasd/interceptShaLou/' + el)
                .then(response => {
                    if (!response.ok) throw new Error('Network response was not ok');
                    return response.blob(); // 使用blob()接收二进制数据
                })
                .then(async res => {
                    let dataUrl = await new Promise((resolve) => {
                        const reader = new FileReader();
                        reader.onloadend = () => resolve(reader.result);
                        reader.readAsDataURL(blob);
                    });
                    let img = new Image();
                    let imgHeight;
                    let imgWidth;
                    img.src = dataUrl;
                    if (img.complete) {
                        imgHeight = img.height
                        imgWidth = img.width
                        setTimeout(() => {
                            let node1 = { type: 'paragraph', children: [{ text: '' }] }
                            SlateTransforms.insertNodes(editor, [node1])
                            let node = { type: 'thumbnail', thumb: data.path, duration: data.duration, href: data.url, uuid: generateUUID().replace(/-/g, ''), src: dataUrl, style: { imgHeight: imgHeight, imgWidth: imgWidth }, children: [{ text: '' }] }
                            SlateTransforms.insertNodes(editor, [node])
                            editor.insertBreak()
                            window.android ?
                                window.android.editorReady(saveDraftShow) :
                                window.webkit.messageHandlers.editorReady.postMessage(saveDraftShow)
                        }, 100)
                    } else {
                        img.onload = await function () {
                            imgHeight = img.height
                            imgWidth = img.width
                        }
                        setTimeout(() => {
                            let node1 = { type: 'paragraph', children: [{ text: '' }] }
                            SlateTransforms.insertNodes(editor, [node1])
                            let node = { type: 'thumbnail', thumb: data.path, duration: data.duration, href: data.url, uuid: generateUUID().replace(/-/g, ''), src: dataUrl, style: { imgHeight: imgHeight, imgWidth: imgWidth }, children: [{ text: '' }] }
                            SlateTransforms.insertNodes(editor, [node])
                            editor.insertBreak()
                            window.android ?
                                window.android.editorReady(saveDraftShow) :
                                window.webkit.messageHandlers.editorReady.postMessage(saveDraftShow)
                        }, 100)
                    }
                })
                .catch(err => {
                    console.log(err)
                });
        }

        //事件派发,(模拟点击工具栏上有序列表按钮和无序列表按钮)
        function emulateMouseClick(element) {
            // 创建事件
            var event = document.createEvent('MouseEvents')
            // 定义事件 参数： type, bubbles, cancelable
            event.initEvent('click', true, true)
            // 触发对象可以是任何元素或其他事件目标
            element.dispatchEvent(event)
        }
        //点击标题input(ios要)
        function titleEditorClick() {
            window.android ? window.android.titleEditorClick() :
                window.webkit.messageHandlers.titleEditorClick.postMessage("")
        }
        //点击编辑器内容区域,点击到img元素时
        function editorClick(event) {
            if (event.target.id == "editor-container") {
                // console.log(editor.getEditableContainer().getElementsByClassName("w-e-scroll")[0])
                // if(editor.selection!=null){
                //     console.log(editor.getSelectionPosition())
                // }
                // setTimeout(() => {
                //     editor.focus(true)
                // })
            }
            if (event.target.nodeName == "IMG" && event.target.id != "video") {
                imgSelection = editor.selection
                window.android ?
                    window.android.imageEdit(nodeValue) :
                    window.webkit.messageHandlers.imageEdit.postMessage(nodeValue)
            } else {
                window.android ? window.android.editorClick() : window.webkit.messageHandlers.editorClick.postMessage("")
            }
        }
        let initFocus = false;
        //编辑器聚焦
        function editorFocus() {
            editor.focus();
        }
        //获取当前的图片和视频列表
        function getImgMap() {
            let arr = [];
            editor.getElemsByType('image').forEach(item => {
                if (item.href) {
                    let p = {};
                    p.id = ""
                    p.path = item.href
                    arr.push(p)
                }
            })
            editor.getElemsByType('thumbnail').forEach(item => {
                let p = {};
                p.id = ""
                p.path = item.href
                arr.push(p)
            })
            return arr
        }
        //app草稿回传
        function setEditorHtml(val) {
            console.log(val.content)
            let valHtml
            notSave = true
            document.getElementById("title").value = val.title
            if (val.title != '') {
                saveDraftShow = true
            }
            let parser = new DOMParser();
            let doc
            if (val.content.includes("html")) {
                console.log("字符串包含子字符串");
                doc = parser.parseFromString(val.content, "text/html");
            } else {
                console.log("字符串不包含子字符串");
                doc = parser.parseFromString('<div id="bodybox">' + val.content + '<div>', "text/html");
            }

            for (let i = val.files.length - 1; i >= 0; i--) {
                if (val.files[i].path.slice(0, 4) == 'http') {
                    val.files.splice(i, 1); // 安全删除
                }
            }
            console.log(val)
            vm._data.index = val.files.length;
            if (!doc.querySelector("bodybox") && (doc.body.textContent.trim() !== '')) {
                valHtml = true
                editorHtmlShow = true
            } else {
                valHtml = false
                editorHtmlShow = false
            }
            for (let item in doc.getElementsByTagName("video")) {
                if (doc.getElementsByTagName("video")[item].id) {
                    vm._data.index++
                }
            }
            for (let item in doc.getElementsByTagName("img")) {

                if (doc.getElementsByTagName("img")[item].id && doc.getElementsByTagName("img")[item].getAttribute("src") != "" && !isBase64(doc.getElementsByTagName("img")[item].src)) {
                    doc.getElementsByTagName("img")[item].dataset.href && doc.getElementsByTagName("img")[item].dataset.href != "" ? doc.getElementsByTagName("img")[item].dataset.href = doc.getElementsByTagName("img")[item].src : ""
                }
            }
            val.files.forEach((item, index) => {
                if (doc.getElementById(item.id)) {

                    if (doc.getElementById(item.id).getAttribute("src") == "" && doc.getElementById(item.id).nodeName != "VIDEO") {
                        console.log(item.path)
                        request({
                            method: "get",
                            url: "/interceptShaLou" + item.path,
                            responseType: "blob"
                        }).then(async res => {
                            var divElement = document.getElementById("obj2");
                            // 使用innerHTML插入内容
                            divElement.innerHTML = res;
                            if (typeof res.data == "string") {
                                doc.getElementById(item.id).src = res.data
                                doc.getElementById(item.id).dataset.href = item.path
                            } else {
                                doc.getElementById(item.id).src = await fileToBase64Async(res.data)
                                if (!res.data.size) {
                                    doc.getElementById(item.id).src = "./file_error.jpeg"
                                }
                                vm._data.html = doc.getElementById("bodybox")
                                vm._data.computedCount++
                            }
                        })
                    } else if (doc.getElementById(item.id).getAttribute("src") == "" && doc.getElementById(item.id).nodeName == "VIDEO") {
                       
                    }
                }
        
            })
      
            for (let item in doc.getElementsByTagName("video")) {
                console.log(doc.getElementsByTagName("video"))
                if (doc.getElementsByTagName("video")) {
                    // doc.getElementsByTagName("video")[item].dataset.href = doc.getElementsByTagName("video")[item].src
                    // doc.getElementsByTagName("video")[item].src = doc.getElementsByTagName("video")[item].poster
                    vm._data.html = doc.getElementById("bodybox")
                    vm._data.computedCount++
                } else if (doc.getElementsByTagName("video")) {
                    // doc.getElementsByTagName("video")[item].dataset.href = doc.getElementsByTagName("video")[item].src
                    // doc.getElementsByTagName("video")[item].src = doc.getElementsByTagName("video")[item].poster
                    vm._data.html = doc.getElementById("bodybox")
                    vm._data.computedCount++
                }
            }
            if (vm._data.index == 0) {
                if (document.getElementById("title").scrollHeight > document.getElementById("title").clientHeight) {
                    document.getElementById("title").style.height = "auto";
                    document.getElementById("title").scrollTop = 0; // 防抖动
                    document.getElementById("title").style.height = 68 + "px";
                }
                let ccc = new XMLSerializer().serializeToString(doc.getElementById("bodybox"))
                ccc = ccc.replace(/<video/gi, "<img")
                ccc = ccc.replace(/<\/video/gi, "</img")
                ccc = ccc.replace(/[\r\n]/gi, "")

                editor.dangerouslyInsertHtml(ccc.slice(ccc.indexOf("bodybox") + 9, ccc.indexOf("</div></body>")))
                editor.focus(true);

                setTimeout(() => {
                    window.android ?
                        window.android.editorReady(valHtml && val.title != '') :
                        window.webkit.messageHandlers.editorReady.postMessage(valHtml && val.title != '')
                    notSave = false
                }, 600)
            }
        }
        //app点击悬浮工具栏样式
        function setSelectionStyle(obj) {
            const nodeEntries = SlateEditor.nodes(editor, {
                match: (node) => {          // JS syntax
                    if (SlateElement.isElement(node)) {
                        if (node.type === 'paragraph') {
                            return true // 匹配 paragraph
                        }
                    }
                    return false
                },
                universal: true,
            })
            if (obj.attribute.split("_")[0] == "font") {

                switch (obj.attribute.split("_")[1]) {

                    case "color": {
                        if (obj.state == 1) {
                            editor.addMark("color", obj.attribute.split("_")[2])
                            return
                        } else {
                            editor.removeMark("color")
                        }
                        break;
                    }
                    case "bg": {
                        if (obj.state == 1) {
                            editor.addMark("bgColor", obj.attribute.split("_")[2])
                        } else {
                            editor.removeMark("bgColor")
                        }
                        break;
                    }
                    case "size": {
                        if (obj.state == 1) {
                            if (obj.attribute.split("_")[2] == "min") {
                                editor.addMark("fontSize", "14px")
                            }
                            if (obj.attribute.split("_")[2] == "normal") {
                                editor.addMark("fontSize", "17px")
                            }
                            if (obj.attribute.split("_")[2] == "big") {
                                editor.addMark("fontSize", "20px")
                            }
                            if (obj.attribute.split("_")[2] == "max") {
                                editor.addMark("fontSize", "22px")
                            }
                        } else {
                            editor.addMark("fontSize", "17px")
                        }
                        break;
                    }
                    case "align": {
                        if (obj.attribute.split("_")[2] == "default") {
                            SlateTransforms.setNodes(editor, {
                                textAlign: "justify"
                            })
                        } else {
                            SlateTransforms.setNodes(editor, {
                                textAlign: obj.attribute.split("_")[2],
                            })
                        }
                        break;
                    }
                    default: {

                        if (obj.state == 1) {
                            Editor.addMark(editor, obj.attribute.split("_")[1], true)
                        } else {
                            editor.removeMark(obj.attribute.split("_")[1])
                        }
                        break;
                    }

                }
            }
            else if (obj.attribute.split("_")[0] == "style") {
                if (obj.attribute.split("_")[1] == "title" && obj.state == 1) {
                    let titleLevel = editor.getElemsByTypePrefix('title1').length + editor.getElemsByTypePrefix('title2').length + editor.getElemsByTypePrefix('title3').length
                    SlateTransforms.setNodes(editor, {
                        level: titleLevel + 1,
                        type: `title${obj.attribute.split("_")[2]}`
                    })
                    editor.addMark("fontSize", "20px");
                } else if (obj.attribute.split("_")[1] == "cite" && obj.state == 1) {

                    let blockquote = `blockquote${obj.attribute.split("_")[2] == 1 ? '2' : obj.attribute.split("_")[2] == 2 ? '' : '3'}`
                    SlateTransforms.setNodes(editor, {
                        type: blockquote
                    })

                } else if (obj.attribute.split("_")[1] == "list" && obj.attribute.split("_")[2] != "3") {
                    let elem = obj.attribute.split("_")[2] == "1" ?
                        document.getElementById("toolbar-container").getElementsByClassName("w-e-bar-item")[16].getElementsByTagName("button")[0]
                        :
                        document.getElementById("toolbar-container").getElementsByClassName("w-e-bar-item")[17].getElementsByTagName("button")[0];
                    emulateMouseClick(elem)
                } else if (obj.attribute.split("_")[1] == "list" && obj.attribute.split("_")[2] == "3") {
                    let node = {
                        type: 'divider', children: [{ text: '' }]
                    }
                    SlateTransforms.insertNodes(editor, [node])
                } else {
                    SlateTransforms.setNodes(editor, {
                        type: "paragraph",
                    })
                }
            } else if (obj.attribute.includes("[")) {

                let emoji = obj.attribute.replace("[", '').replace("]", '')
                editor.insertText(emoji)
                // let node = {
                //     type: 'emoji', src: "https://formal.resources.yaoxuntong.cn/imgs/emoji/[OK]@2x.png", style: {
                //         height: "20px;", width: "20px",
                //     }, children: [{ text: '' }]
                // }
                // SlateTransforms.insertNodes(editor, [node])
                //     let node1 = {
                //     type: 'emoji', src: "https://formal.resources.yaoxuntong.cn/imgs/emoji/[酷]@2x.png" ,  style: {
                //     width:'100px',height:'100px'}, children: [{ text: '' }]
                //     }
                // SlateTransforms.insertNodes(editor, [node1])
                // let node = {
                //     type: 'emoji', src: `https://formal.resources.yaoxuntong.cn/imgs/emoji/${obj.attribute}@2x.png` ,  style: {
                //     width:'20px',height:'20px'}, children: [{ text: '' }]
                // }

                // SlateTransforms.insertNodes(editor, [node])
                // editor.selection=null
                // editor.restoreSelection()
                // let node1 = { type: 'paragraph', children: [{ text: '' }] }
                // SlateTransforms.insertNodes(editor, [node1])
                // setTimeout(()=>{
                //     SlateTransforms.mergeNodes(editor)
                // })
                // SlateTransforms.setNodes(editor, {
                //         type: "paragraph",
                //     })
            } else {

                obj.attribute == "redo" ? editor.redo() : "";
                obj.attribute == "undo" ? editor.undo() : "";
            }
        }
        //获取编辑器html
        function getEditorHtml(isTitle) {
            let errorMsg = "";
            let hasErrorImg = false;
            let files = [];
            let parser = new DOMParser();
            let doc = parser.parseFromString(editor.getHtml(), "text/html");
            for (let item in doc.getElementsByTagName("img")) {
                if (doc.getElementsByTagName("img")[item].id) {
                    if (isBase64(doc.getElementsByTagName("img")[item].src)) {
                        files.push({
                            id: doc.getElementsByTagName("img")[item].id,
                            path: doc.getElementById(doc.getElementsByTagName("img")[item].id).getAttribute("data-href")
                        })
                        doc.getElementById(doc.getElementsByTagName("img")[item].id).setAttribute("src", "")
                    } else if (doc.getElementsByTagName("img")[item].getAttribute("src") != "") {
                        if (doc.getElementsByTagName("img")[item].getAttribute("src").includes("./file_error.jpeg")) {
                            hasErrorImg = true
                        } else {
                            doc.getElementById(doc.getElementsByTagName("img")[item].id).setAttribute("data-href", doc.getElementsByTagName("img")[item].src)
                            files.push({
                                id: doc.getElementsByTagName("img")[item].id,
                                path: doc.getElementById(doc.getElementsByTagName("img")[item].id).getAttribute("data-href")
                            })
                        }
                    }
                }
            }
            for (let item in doc.getElementsByTagName("video")) {
                if (doc.getElementsByTagName("video")[item].id) {
                    if (isBase64(doc.getElementsByTagName("video")[item].src)) {
                        files.push({
                            id: doc.getElementsByTagName("video")[item].id,
                            path: doc.getElementById(doc.getElementsByTagName("video")[item].id).getAttribute("data-href"),
                            duration: doc.getElementById(doc.getElementsByTagName("video")[item].id).getAttribute("data-duration"),
                        })
                        doc.getElementsByTagName("video")[item].src = ""
                    } else if (doc.getElementsByTagName("video")[item].getAttribute("src") != "") {
                        doc.getElementsByTagName("video")[item].dataset.thumb = doc.getElementsByTagName("video")[item].src
                        files.push({
                            id: doc.getElementsByTagName("video")[item].id,
                            path: doc.getElementById(doc.getElementsByTagName("video")[item].id).getAttribute("data-href"),
                            duration: doc.getElementById(doc.getElementsByTagName("video")[item].id).getAttribute("data-duration"),
                        })
                    }
                }
            }
            let newDoc = new XMLSerializer().serializeToString(doc);
            let html1 = newDoc.slice(0, newDoc.indexOf("<head>") + 6) + `<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <meta charset="UTF-8" />
  <meta http-equiv="Pragma" content="no-cache">
  <title>${document.getElementById("title").innerHTML}</title>
  <style>
  img {
        width: 100%;
    }
    body {
        margin: 0 15px;
    }
    * {
        word-break: normal;
        text-align: justify;
    }
    #title {
        margin-bottom: 8px;
        text-align: center;
        font-size: 19px;
        font-weight: 700;
        color: #1a1c27;
        text-align: left;
        font-family: 黑体;
    }
    p {
        word-break: break-all;
        word-wrap: break-word;
    }
@supports(-webkit-touch-callout:none) {
    p {
        word-break:break-word;
        word-wrap: break-word;
    }
}
    table {
        border-top: 1px solid #ccc;
        border-left: 1px solid #ccc;
        width: 100%
    }
    /* blockquote 样式 */
    blockquote {
        display: block;
        border-left: 8px solid #000
        padding: 5px 10px;
        margin: 10px 0;
        line-height: 1.4;
        font-size: 100%;
        background-color: #f1f1f1;
    }
    /* ul ol 样式 */
    ul,
    ol {
        margin: 10px 0 10px 0px;
    }
    .open {
        display: none;
    }
</style>`+ newDoc.slice(newDoc.indexOf("<head>") + 6);
            let ctime = `${new Date().getFullYear()}-${new Date().getMonth() + 1}-${new Date().getDate()} ${new Date().getHours()}:${new Date().getMinutes()}:${new Date().getSeconds()}`
            html2 = html1.slice(0, html1.indexOf("<body>") + 6) + `<div id="bodybox">` + html1.slice(html1.indexOf("<body>") + 6, html1.indexOf("</body>")) + `</div>` + html1.slice(html1.indexOf("</body>"))
            html2 = html2.replace(`<div id="bodybox"><p><br/></p>`, `<div id="bodybox">`)
            let titleEle = document.getElementById("title")
            if (titleEle && (titleEle.value.length < 2 || titleEle.value.length > 30)) {
                errorMsg = "请输入2-30个字的标题"
            } else if (editor.getText().trim().length == 0 && files.length == 0) {
                errorMsg = "请输入正文"
            } else if (hasErrorImg) {
                errorMsg = "文章图片/视频资源加载失败,请重新上传"
            } else {
                errorMsg = ""
            }
            let editorObj = {
                content: html2,
                contentBrief: editor.getText().trim().slice(0, 301),
                files: files,
                title: document.getElementById("title").value,
                contentLength: editor.getText().trim().length,
                isTitle: isTitle,
                isEmoji: editor.getElemsByType("emoji").length > 0 ? 1 : 0,
                errorMsg: errorMsg,
                // click: saveDraftShow && editorHtmlShow
                click: (editor.getText().trim().slice(0, 301) != "" || files.length > 0) && document.getElementById("title").value.length >= 2

            }
            editorHtmlIosData = editorObj
            console.log(html2)
            return editorObj;
        }


        function editorHtmlIos() {
            if (isIOS()) {
                window.webkit.messageHandlers.editorHtmlIos.postMessage(JSON.stringify(editorHtmlIosData))
            }
        }
        function isIOS() {
            return /iPad|iPhone|iPod/.test(navigator.userAgent) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
        }
        function deleteForward() {//删除内容
            console.log(editor.deleteBackward())
        }
    </script>
</body>

</html>